<?php
namespace App\Supports\Qrcode;

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Support\Facades\File;
use Endroid\QrCode\Encoding\Encoding;
use Illuminate\Support\Facades\Storage;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeNone;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;

class Qrcode
{
	protected $data;
	
	public function __construct()
	{
		if (! File::isDirectory(public_path('temp/userinviteqrcodes'))) {
			File::makeDirectory(public_path('temp/userinviteqrcodes'), 755, true, true);
		}
	}
	
	protected function build()
	{
		return Builder::create()
			->writer(new PngWriter())->writerOptions([])
			->data($this->data)->encoding(new Encoding('UTF-8'))
			->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
			->size(300)->margin(10)->roundBlockSizeMode(new RoundBlockSizeModeNone())
			->build();
	}
	
	public function make(string $data, string $name)
	{
		$this->data = $data;
		$qrcode = $this->build();
		$savePath = public_path("temp/userinviteqrcodes/{$name}.png");
		$qrcode->saveToFile($savePath);
		
		// move to oss.
		$remotePath = "images/userinviteqrcodes";
		Storage::putFileAs($remotePath, $savePath, "{$name}.png");
		
		// remove local qrcode.
		File::delete($savePath);
		
		return Storage::url("{$remotePath}/{$name}.png");
	}
}
